package cn.edu.sziit.bbs.controller;

import cn.edu.sziit.bbs.model.Post;
import cn.edu.sziit.bbs.model.User;
import cn.edu.sziit.bbs.service.PostService;
import cn.edu.sziit.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//post.jsp
@Controller
public class PostController {

    @Autowired
    private PostService postService;
//    @Autowired
//    private UserService userService;

    /**
     * 跳转到post.jsp发帖页面
     *
     * @return
     */
    @RequestMapping(value = "/post", method = RequestMethod.GET)
    public String postShow() {
        return "post";
    }

    /**
     * 帖子的验证和插入
     *
     * @param post
     * @param file
     * @param request
     * @param session
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/post", method = RequestMethod.POST, produces = "application/json;" +
            "charset=UTF-8")
    public Map<String, String> postCreate(Post post, MultipartFile file,
                                          HttpServletRequest request, HttpSession session) throws IOException {
        Map<String, String> map = new HashMap<>();
        if (post.getPostTitle() == null) {
            System.out.println("标题不能为空");
            map.put("info", "标题不能为空");
            return map;
        }
        if (post.getPostContent() == null) {
            System.out.println("内容不能为空");
            map.put("info", "内容不能为空");
            return map;
        }
        if (!file.getOriginalFilename().equals("")) {
            System.out.println(file.getOriginalFilename());
            String path = request.getServletContext().getRealPath("/static/images/post");
            System.out.println("path:" + path);
            File pathFile = new File(path);
            if (!pathFile.exists()) {
                System.out.println("目录创建成功");
                pathFile.mkdir();
            }
            System.out.println(pathFile.getCanonicalPath());
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            File serverFile = new File(path, fileName);
            file.transferTo(serverFile);

            post.setPostPhoto("/static/images/post/" + fileName);
        }
//        session.setAttribute("user", userService.selectByUsername("user5"));
        User user = (User) session.getAttribute("user");
        post.setUserId(user.getUserId());
        post.setUserName(user.getUserName());
        System.out.println(post);

        postService.insert(post);
        map.put("info", "帖子发表成功");
        session.setAttribute("page", "");
        return map;
    }
}
